const fs = require('fs');
const Path = require('path');
const crypto = require('crypto');

class Server {

	constructor() {

	}

	/**
	 * base64
	 * @param ctx 环境上下文
	 */
	static base64 (ctx) {
		const {code, type} = ctx.vals
		switch (type) {
			case 'encode':
				return new Buffer.from(code).toString('base64');
			case 'decode':
				return new Buffer.from(code, 'base64').toString();
			case 'hexEncode':
				return new Buffer.from(code, 'base64').toString('hex')
			case 'hexDecode':
				return new Buffer.from(code, 'hex').toString('utf8')
		}
	}

	/**
	 * 图片转Base64
	 * @param ctx 环境上下文
	 */
	static imageToBase64 (ctx) {
		const {imageUrl} = ctx.vals
		let bitmap = fs.readFileSync(imageUrl);
		return new Buffer.from(bitmap).toString('base64');
	}

	/**
	 * base64转图片
	 * @param ctx 环境上下文
	 */
	static base64ToImage (ctx) {
		const { imageStr } = ctx.vals
		const webUrl = `/up_data/base64_${(new Date().getTime())}_${String(Math.random()).split('.')[1]}`
		const url = Path.resolve(__dirname, '../../static') + webUrl
		fs.writeFileSync(url, new Buffer.from(imageStr, 'base64'));
		return `/ybweb${webUrl}`
	}

	/**
	 * md5
	 * @param ctx 环境上下文
	 */
	static md5 (ctx) {
		const {input, key, type} = ctx.vals
		const hash = key ? crypto.createHmac(type, key) : crypto.createHash(type)
		hash.update(input);
		return hash.digest('hex')
	}

	/**
	 * aes
	 * @param ctx 环境上下文
	 */
	static aes (ctx) {
		const {input, key, type} = ctx.vals

		function aesEncrypt(data, key) {
			const cipher = crypto.createCipher('aes192', key);
			let crypted = cipher.update(data, 'utf8', 'hex');
			crypted += cipher.final('hex');
			return crypted;
		}

		function aesDecrypt(encrypted, key) {
			const decipher = crypto.createDecipher('aes192', key);
			let decrypted = decipher.update(encrypted, 'hex', 'utf8');
			decrypted += decipher.final('utf8');
			return decrypted;
		}

		return type === 'encode' ? aesEncrypt(input, key) : aesDecrypt(input, key)
	}
}

module.exports = Server
